package com.m3958.firstgwt.server.filter;

import java.io.IOException;
import java.io.Writer;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import redis.clients.jedis.Jedis;

import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Singleton;
import com.m3958.firstgwt.server.service.JedisPoolService;
import com.m3958.firstgwt.server.service.RequestScopeObjectService;
import com.m3958.firstgwt.server.utils.StringUtils;


@Singleton
public class ContentCacheFilter implements Filter {
	
	private ServletContext sc;
	private FilterConfig fc;
  
	@Inject
	private Injector injector;
	
	private Logger logger = Logger.getLogger(this.getClass().getName());
	
	@Inject
	private JedisPoolService jpservice;
	
	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
                       FilterChain chain)
                       throws IOException, ServletException {
	    HttpServletRequest req = (HttpServletRequest) request;
	    HttpServletResponse res = (HttpServletResponse) response;
	    RequestScopeObjectService rso = injector.getInstance(RequestScopeObjectService.class);
    
		if(rso.getRequestWebSite() == null || !rso.getRequestWebSite().isCacheEnable()){
	    	chain.doFilter(req, res);
	    	return;
		}
    	String etag = req.getHeader("If-None-Match");
    	String rurl = StringUtils.getCacheString(req.getRequestURI(),req.getQueryString());
    	Map<String, String> cc = null;
    	
    	Jedis jd = jpservice.getInstance();
    	try {
			if(etag == null){
				cc = jd.hgetAll(rurl);
				if(!cc.isEmpty()){
					String content = cc.get("content");
					res.setContentType("text/html; charset=UTF-8");
					res.setCharacterEncoding("UTF-8");
					res.setHeader("ETag", cc.get("etag"));
					res.setContentLength(content.getBytes("UTF8").length);
					Writer writer = res.getWriter();
					writer.write(content);
					writer.close();
					return;
				}
			}else{
				String jrurl = jd.get(etag);
				logger.log(Level.INFO,"jurl:" + jrurl + ",rurl" + rurl);
				if(rurl.equals(jrurl)){
					res.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
					return;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			jpservice.putBack(jd);
		}
   		chain.doFilter(req, res);//继续
	}
  
	@Override
	public void init(FilterConfig filterConfig) {
		this.fc = filterConfig;
		this.sc = filterConfig.getServletContext();
	}

	public void destroy() {
		this.sc = null;
		this.fc = null;
	}
}
